<template>
  <view class="fault-order-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="故障工单" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 工单状态筛选 -->
            <view class="filter-item">
              <text class="filter-label">工单状态：</text>
              <up-tabs :list="statusList" :scrollable="false" @change="handleStatusChange"
                :current="currentStatus"></up-tabs>
            </view>

            <!-- 时间筛选 -->
            <view class="filter-item">
              <text class="filter-label">时间筛选：</text>
              <up-tabs :list="timeRangeList" :scrollable="true" @change="handleTimeRangeChange"
                :current="currentTimeRange"></up-tabs>
            </view>

            <!-- 自定义时间选择 -->
            <view v-if="currentTimeRange === 5" class="custom-time-section">
              <view class="time-picker-row">
                <view class="time-picker">
                  <text class="title">自定义时间</text>
                  <uni-datetime-picker type="daterange" :border="false" v-model="customTimeRange.dateRange"
                    @change="handleDateRangeChange"></uni-datetime-picker>
                </view>
              </view>
            </view>

            <!-- 泊位号搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.berthNumber" :clearabled="true" :showAction="true" placeholder="请输入泊位号"
                @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="fault-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              工单编号：<text class="number">{{ item.orderNo }}</text>
            </view>
            <view class="status-badge" :class="getStatusClass(item.status)">
              {{ getStatusText(item.status) }}
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">负责人：</text>
                <text class="value">{{ item.assigneeName || '未指派' }}</text>
              </view>
              <view class="item">
                <text class="label">异常类型：</text>
                <text class="value exception-type">故障工单</text>
              </view>
              <view class="item">
                <text class="label">泊位号：</text>
                <text class="value">{{ item.berthNumber }}</text>
              </view>
              <view class="item">
                <text class="label">设备编号：</text>
                <text class="value">{{ item.deviceSN }}</text>
              </view>
              <view class="item">
                <text class="label">停车场：</text>
                <text class="value">{{ item.parkingLot }}</text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="info" text="查看详情" class="custom-style" @click="handleViewDetail(item)"></up-button>
                <!-- <up-button v-if="item.status === 'pending'" type="primary" text="故障处理" class="custom-style"
                  @click="handleFaultProcess(item)"></up-button>
                <up-button type="warning" text="故障上报" class="custom-style" @click="handleFaultReport"></up-button> -->
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 故障上报弹窗 -->
    <up-popup :show="showReportModal" mode="center" :round="10">
      <view class="report-modal">
        <view class="modal-header">
          <text class="modal-title">故障上报</text>
          <up-icon name="close" @click="closeReportModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">选择负责人：</text>
            <up-search v-model="reportForm.inspectorKeyword" placeholder="搜索巡检员或客服人员"
              @search="searchInspector"></up-search>
            <view class="inspector-list">
              <view class="inspector-item" v-for="inspector in filteredInspectors" :key="inspector.id"
                @click="selectInspector(inspector)"
                :class="{ active: reportForm.selectedInspector?.id === inspector.id }">
                <text class="inspector-name">{{ inspector.name }}</text>
                <text class="inspector-phone">{{ inspector.phone }}</text>
              </view>
            </view>
          </view>
          <view class="form-item">
            <text class="form-label">泊位号：</text>
            <up-input v-model="reportForm.berthNumber" placeholder="请输入泊位号"></up-input>
          </view>
          <view class="form-item">
            <text class="form-label">设备编号：</text>
            <up-input v-model="reportForm.deviceSN" placeholder="请输入设备编号"></up-input>
          </view>
          <view class="form-item">
            <text class="form-label">处理状态：</text>
            <up-radio-group v-model="reportForm.status">
              <up-radio label="pending" name="pending">待处理</up-radio>
              <up-radio label="completed" name="completed">已处理</up-radio>
            </up-radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">上传图片：</text>
            <up-upload :file-list="reportForm.images" @after-read="afterRead" @delete="deleteImage" :max-count="3"
              :image-fit="'cover'" multiple></up-upload>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="reportForm.remark" placeholder="请输入备注信息" maxlength="200"></up-textarea>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeReportModal">取消</up-button>
          <up-button type="primary" @click="confirmReport">确认上报</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 故障处理弹窗 -->
    <up-popup v-model:show="showProcessModal" mode="center" :round="10">
      <view class="process-modal">
        <view class="modal-header">
          <text class="modal-title">故障处理</text>
          <up-icon name="close" @click="closeProcessModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="form-item">
            <text class="form-label">处理状态：</text>
            <up-radio-group v-model="processForm.status">
              <up-radio label="completed" name="completed">已处理</up-radio>
            </up-radio-group>
          </view>
          <view class="form-item">
            <text class="form-label">上传图片：</text>
            <up-upload :file-list="processForm.images" @after-read="afterProcessRead" @delete="deleteProcessImage"
              :max-count="3" :image-fit="'cover'" multiple></up-upload>
          </view>
          <view class="form-item">
            <text class="form-label">备注：</text>
            <up-textarea v-model="processForm.remark" placeholder="请输入备注信息" maxlength="200"></up-textarea>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeProcessModal">取消</up-button>
          <up-button type="primary" @click="confirmProcess">确认处理</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 查看详情弹窗 -->
    <up-popup v-model:show="showDetailModal" mode="center" :round="10">
      <view class="detail-modal">
        <view class="modal-header">
          <text class="modal-title">工单详情</text>
          <up-icon name="close" @click="closeDetailModal"></up-icon>
        </view>
        <view class="modal-content">
          <view class="detail-item">
            <text class="detail-label">工单编号：</text>
            <text class="detail-value">{{ currentDetail.orderNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">泊位编号：</text>
            <text class="detail-value">{{ currentDetail.berthNumber }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">设备编号：</text>
            <text class="detail-value">{{ currentDetail.deviceSN }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">异常类型：</text>
            <text class="detail-value">故障工单</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">停车场：</text>
            <text class="detail-value">{{ currentDetail.parkingLot }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">负责人：</text>
            <text class="detail-value">{{ currentDetail.assigneeName || '未指派' }}</text>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="primary" @click="closeDetailModal">关闭</up-button>
        </view>
      </view>
    </up-popup>

    <!-- 悬浮按钮已移除，故障上报按钮已移至每个工单项中 -->
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { getFaultJobList } from '@/api';

// 工单状态选项
const statusList = [
  { name: '全部' },
  { name: '待处理' },
  { name: '已处理' },
];
const currentStatus = ref(0);

// 时间筛选选项
const timeRangeList = [
  { name: '近7天' },
  { name: '近1个月' },
  { name: '近3个月' },
  { name: '近半年' },
  { name: '近1年' },
  { name: '自定义' },
];
const currentTimeRange = ref(0);

// 自定义时间范围
const customTimeRange = reactive({
  startTime: '',
  endTime: '',
  dateRange: []
});

// 搜索表单数据
const searchForm = reactive({
  berthNumber: '',
});

// z-paging 组件引用
const paging = ref(null);

// 当前显示的列表数据
const currentList = ref([]);

// 故障上报相关
const showReportModal = ref(false);
const reportForm = reactive({
  inspectorKeyword: '',
  selectedInspector: null,
  berthNumber: '',
  deviceSN: '',
  status: 'pending',
  images: [],
  remark: ''
});

// 故障处理相关
const showProcessModal = ref(false);
const processForm = reactive({
  status: 'completed',
  images: [],
  remark: ''
});
const currentProcessItem = ref(null);

// 巡检员和客服人员列表
const inspectorList = ref([
  { id: 1, name: '张三', phone: '13800138001', type: '巡检员' },
  { id: 2, name: '李四', phone: '13800138002', type: '巡检员' },
  { id: 3, name: '王五', phone: '13800138003', type: '客服' },
  { id: 4, name: '赵六', phone: '13800138004', type: '客服' },
]);

// 过滤后的巡检员列表
const filteredInspectors = computed(() => {
  if (!reportForm.inspectorKeyword) {
    return inspectorList.value;
  }
  return inspectorList.value.filter(inspector =>
    inspector.name.includes(reportForm.inspectorKeyword) ||
    inspector.phone.includes(reportForm.inspectorKeyword) ||
    inspector.type.includes(reportForm.inspectorKeyword)
  );
});

// 查看详情相关
const showDetailModal = ref(false);
const currentDetail = ref({});

// 工单状态切换事件
const handleStatusChange = (e) => {
  currentStatus.value = e.index;
  if (paging.value) {
    paging.value.reload();
  }
};

// 时间筛选切换事件
const handleTimeRangeChange = (e) => {
  currentTimeRange.value = e.index;
  // 如果不是自定义时间范围，则清空自定义时间
  if (currentTimeRange.value !== 5) {
    customTimeRange.dateRange = [];
    customTimeRange.startTime = '';
    customTimeRange.endTime = '';
  }
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理日期范围变化
const handleDateRangeChange = (e) => {
  if (Array.isArray(e) && e.length === 2) {
    customTimeRange.startTime = e[0];
    customTimeRange.endTime = e[1];
    if (paging.value) {
      paging.value.reload();
    }
  }
};

// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 清空搜索
const handleClear = () => {
  searchForm.berthNumber = '';
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.navigateTo({
    url: '/pages/work-order/index'
  });
};

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    'pending': 'status-pending',
    'completed': 'status-completed'
  };
  return statusMap[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'completed': '已处理'
  };
  return statusMap[status] || status;
};

// 故障上报
const handleFaultReport = () => {
  resetReportForm();
  showReportModal.value = true;
};

// 重置上报表单
const resetReportForm = () => {
  reportForm.selectedInspector = null;
  reportForm.inspectorKeyword = '';
  reportForm.berthNumber = '';
  reportForm.deviceSN = '';
  reportForm.status = 'pending';
  reportForm.images = [];
  reportForm.remark = '';
};

// 搜索巡检员或客服
const searchInspector = () => {
  // 搜索逻辑已在computed中实现
};

// 选择巡检员或客服
const selectInspector = (inspector) => {
  reportForm.selectedInspector = inspector;
};

// 上传图片后的回调
const afterRead = (event) => {
  const { file } = event.detail;
  // 这里应该调用上传API，这里简化处理
  const fileList = [].concat(file);
  fileList.forEach(item => {
    reportForm.images.push({
      url: item.url,
      status: 'done',
      message: '上传成功',
      name: item.name
    });
  });
};

// 删除图片
const deleteImage = (event) => {
  const { index } = event.detail;
  reportForm.images.splice(index, 1);
};

// 确认上报
const confirmReport = () => {
  if (!reportForm.selectedInspector) {
    uni.showToast({
      title: '请选择负责人',
      icon: 'none'
    });
    return;
  }

  if (!reportForm.berthNumber) {
    uni.showToast({
      title: '请输入泊位号',
      icon: 'none'
    });
    return;
  }

  if (!reportForm.deviceSN) {
    uni.showToast({
      title: '请输入设备编号',
      icon: 'none'
    });
    return;
  }

  // 这里应该调用API进行上报
  uni.showToast({
    title: '上报成功',
    icon: 'success'
  });

  closeReportModal();
  if (paging.value) {
    paging.value.reload();
  }
};

// 关闭上报弹窗
const closeReportModal = () => {
  showReportModal.value = false;
};

// 故障处理
const handleFaultProcess = (item) => {
  currentProcessItem.value = item;
  processForm.status = 'completed';
  processForm.images = [];
  processForm.remark = '';
  showProcessModal.value = true;
};

// 上传处理图片后的回调
const afterProcessRead = (event) => {
  const { file } = event.detail;
  // 这里应该调用上传API，这里简化处理
  const fileList = [].concat(file);
  fileList.forEach(item => {
    processForm.images.push({
      url: item.url,
      status: 'done',
      message: '上传成功',
      name: item.name
    });
  });
};

// 删除处理图片
const deleteProcessImage = (event) => {
  const { index } = event.detail;
  processForm.images.splice(index, 1);
};

// 确认处理
const confirmProcess = () => {
  if (!processForm.remark) {
    uni.showToast({
      title: '请输入备注信息',
      icon: 'none'
    });
    return;
  }

  // 这里应该调用API进行处理
  uni.showToast({
    title: '处理成功',
    icon: 'success'
  });

  closeProcessModal();
  if (paging.value) {
    paging.value.reload();
  }
};

// 关闭处理弹窗
const closeProcessModal = () => {
  showProcessModal.value = false;
};

// 查看详情
const handleViewDetail = (item) => {
  currentDetail.value = item;
  showDetailModal.value = true;
};

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false;
};

// 获取故障工单列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 构建API请求参数
    const params = {
      pageNum: pageNo,
      pageSize: pageSize,
      status: currentStatus.value === 0 ? -1 : currentStatus.value, // 0:全部(-1) 1:待处理 2:已处理
      keyword: searchForm.berthNumber || '', // 泊位关键字
      dateType: currentTimeRange.value === 5 ? -1 : currentTimeRange.value, // 日期类型
    };

    // 如果是自定义时间，添加时间参数
    if (currentTimeRange.value === 5 && customTimeRange.dateRange && customTimeRange.dateRange.length === 2) {
      params.startDate = customTimeRange.dateRange[0];
      params.endDate = customTimeRange.dateRange[1];
    }

    // 调用API获取数据
    const res = await getFaultJobList(params);

    if (res && res.success) {
      // 处理返回的数据
      const records = res.data.records || [];
      const total = res.data.total || 0;

      // 转换数据格式
      const formattedList = records.map(item => {
        return {
          orderNo: item.bizCode || '', // 工单ID
          status: item.zpType === '0' ? 'pending' : 'completed', // 指派状态转换为前端状态
          assigneeName: item.inspectorName || '未指派', // 指派运维人员名字
          berthNumber: item.berthNo || '', // 泊位号
          deviceSN: item.deviceSn || '', // 设备编号
          parkingLot: item.veName || '', // 场地名字
          inspectorId: item.inspectorId || '', // 指派运维人员ID
          veId: item.veId || '', // 场地ID
          createTime: item.createTime || '', // 创建时间
          errorType: item.errorType || '', // 工单类型
          errorTypeName: item.errorTypeName || '故障工单' // 异常类型名字
        };
      });

      // 返回处理后的数据和总数
      paging.value.complete(formattedList || []);
    } else {
      uni.showToast({
        title: res?.msg || '获取数据失败',
        icon: 'none'
      });
      return {
        list: [],
        total: 0
      };
    }
  } catch (error) {
    console.error('获取故障工单列表失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
    return {
      list: [],
      total: 0
    };
  }
};

// 页面挂载时获取数据
onMounted(() => {
  if (paging.value) {
    paging.value.reload();
  }
});
</script>

<style scoped lang="scss">
.fault-list {
  padding: 20px;
}

.filter-section {
  .filter-item {
    margin-bottom: 20rpx;

    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }
  }

  .custom-time-section {
    margin-top: 20rpx;

    .time-picker-row {
      display: flex;
      align-items: center;

      .time-picker {
        width: 100%;
        display: flex;
        align-items: center;
        background-color: #f8f8f8;
        padding: 10rpx 20rpx;
        border-radius: 8rpx;
        margin-bottom: 20rpx;

        .title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-right: 20rpx;
        }
      }

      .time-separator {
        font-size: 28rpx;
        color: #666;
        margin: 0 10rpx;
      }
    }
  }
}

// 列表卡片样式
.list-item-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .card-header {
    padding: 24rpx 30rpx 16rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;

      .number {
        color: #1890ff;
      }
    }

    .status-badge {
      padding: 8rpx 16rpx;
      border-radius: 20rpx;
      font-size: 22rpx;

      &.status-pending {
        background: #fff2e8;
        color: #fa8c16;
      }

      &.status-completed {
        background: #f6ffed;
        color: #52c41a;
      }
    }
  }

  .card-content-box {
    padding: 20rpx 30rpx;

    .content {
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          font-size: 26rpx;
          color: #666;
          flex-shrink: 0;
        }

        .value {
          font-size: 26rpx;
          color: #333;
          text-align: right;

          &.exception-type {
            font-weight: bold;
            color: #f5222d;
          }
        }
      }
    }

    .card-footer {
      margin-top: 24rpx;
      padding-top: 20rpx;
      border-top: 1px solid #f5f5f5;

      .operate {
        display: flex;
        justify-content: flex-end;
        gap: 20rpx;

        .custom-style {
          border-radius: 8rpx;
          font-size: 24rpx;
        }
      }
    }
  }
}

// 弹窗样式
.report-modal,
.process-modal,
.detail-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;

  .modal-header {
    padding: 30rpx;
    border-bottom: 1px solid #f5f5f5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .modal-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .modal-content {
    padding: 30rpx;
    max-height: 600rpx;
    overflow-y: auto;

    .form-item,
    .detail-item {
      margin-bottom: 30rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .form-label,
      .detail-label {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 10rpx;
        display: block;
      }

      .detail-value {
        font-size: 28rpx;
        color: #666;
      }
    }

    .inspector-list {
      max-height: 300rpx;
      overflow-y: auto;
      border: 1px solid #f0f0f0;
      border-radius: 8rpx;
      margin-top: 10rpx;

      .inspector-item {
        padding: 20rpx;
        border-bottom: 1px solid #f5f5f5;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &:last-child {
          border-bottom: none;
        }

        &.active {
          background: #e6f7ff;
          color: #1890ff;
        }

        .inspector-name {
          font-size: 28rpx;
          font-weight: bold;
        }

        .inspector-phone {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }

  .modal-footer {
    padding: 30rpx;
    border-top: 1px solid #f5f5f5;
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
  }
}

// 悬浮按钮
.float-button {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  width: 120rpx;
  height: 120rpx;
  background-color: #1890ff;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
  z-index: 999;

  text {
    font-size: 24rpx;
    color: #fff;
    margin-top: 6rpx;
  }
}
</style>